
var ws;
var textDecoder = new TextDecoder();
var textEncoder = new TextEncoder();

$(document).ready(function(){
    var authToken = getLocal("authToken")
    console.log()
    if (authToken == null || authToken == "null" || authToken == ""){
        location.href="login.html"
        return
    } else {
        console.log("authToken:"+authToken)
    }

    $(".input-box").keypress(function(e){
        if (e.which==13){
            var txt = $(this).val();
            if (txt != "") {
                appendMessage("我", $(this).val())
                $(this).val("")
            }
        }
    })

    ws = new WebSocket(socketUrl);

    ws.onopen = function(){
        ws.binaryType = 'arraybuffer';
        buildConnect(ws, authToken)
    }

    ws.onmessage = receiveMessage;
})

function send(){
    console.log("click send")
}

function logout(){
    let authInfo = {
        authToken: getLocal("authToken")
    };
    setLocal("authToken", null)
    $.ajax({
        type: "POST",
        dataType: "json",
        url: apiUrl+"/user/logout",
        data: JSON.stringify(authInfo),
        success: function(result) {
            if (result.code == 0) {
                window.location.href = "/login.html";
            } else {
                swal("request error, please login!");
            }
        },
        error: function(){
            swal("sorry, exception! ")
        }
    });
    window.location.href = "/index.html";
}

function appendMessage(name,m) {
    var log = $(".log-box");
    log.append('<p class="msg-context">'+name+': '+m+'</p>')
    log.scrollTop(log[0].scrollHeight);
}

function sendWebSocket(conn, op, seq, msg){
    var headerBuf = new ArrayBuffer(RawHeaderLen);
    var headerView = new DataView(headerBuf, 0);
    var bodyBuf = textEncoder.encode(msg);
    headerView.setUint8(0, 'v');
    headerView.setUint8(1, 'w');
    headerView.setInt16(VersionOffset, 1);
    headerView.setInt16(LengthOffset, RawHeaderLen + bodyBuf.byteLength)
    headerView.setInt16(OptionOffset, op);
    headerView.setInt16(SeqOffset, seq);
    conn.send(mergeArrayBuffer(headerBuf, bodyBuf));
}

function buildConnect(conn, token){
    let data = {authToken: token}
    sendWebSocket(ws, OpBuildConn, 0, JSON.stringify(data))
}

function mergeArrayBuffer(lbuf, rbuf){
    var u81 = new Uint8Array(lbuf);
    var u82 = new Uint8Array(rbuf);
    var res = new Uint8Array(u81.byteLength+u82.byteLength);
    res.set(u81, 0);
    res.set(u82, u81.byteLength)
    return res.buffer
}

document.onkeydown = function(k) {
    if (k.ctrlKey && k.code=="KeyS") {
        return false;
    }
}

function receiveMessage(evt){
    var data = evt.data;
    console.log("recevie message."+data)
    var dataView = new DataView(data, 0);
    var Version = dataView.getInt16(VersionOffset);
    var Length = dataView.getInt16(LengthOffset);
    var Option = dataView.getInt16(OptionOffset);
    var Seq = dataView.getInt16(SeqOffset);
    var msgBody = textDecoder.decode(data.slice(RawHeaderLen, Length));

    switch (Option) {
        case OpSingleSend:
            var msg = JSON.parse(msgBody);
            appendMessage(msg.FromUserId, msg.MsgData);
            break;
        case OpSingleSendAck:
            break;
        case OpKickUserOnline:
            break;
        case OpKickUserOffline:
            break;
        default:
            console.log("message=", msgBody);
    }
}